package com.zy.design.demo.behavioral;

import java.util.HashMap;
import java.util.Map;

// 中介者接口
interface Mediator {
    void register(String deviceName, Device device);  // 注册设备
    void relay(String sender, String message);        // 设备之间的消息传递
}

// 设备类：代表家电设备
abstract class Device {
    protected Mediator mediator;
    protected String name;

    public Device(String name, Mediator mediator) {
        this.name = name;
        this.mediator = mediator;
    }

    public abstract void send(String message);
    public abstract void receive(String message);
}

// 具体设备：灯
class Light extends Device {
    public Light(Mediator mediator) {
        super("Light", mediator);
    }

    @Override
    public void send(String message) {
        System.out.println(name + " sending message: " + message);
        mediator.relay(name, message);  // 通过中介者发送消息
    }

    @Override
    public void receive(String message) {
        System.out.println(name + " received message: " + message);
    }
}

// 具体设备：电视
class TV extends Device {
    public TV(Mediator mediator) {
        super("TV", mediator);
    }

    @Override
    public void send(String message) {
        System.out.println(name + " sending message: " + message);
        mediator.relay(name, message);  // 通过中介者发送消息
    }

    @Override
    public void receive(String message) {
        System.out.println(name + " received message: " + message);
    }
}

// 具体设备：空调
class AirConditioner extends Device {
    public AirConditioner(Mediator mediator) {
        super("AirConditioner", mediator);
    }

    @Override
    public void send(String message) {
        System.out.println(name + " sending message: " + message);
        mediator.relay(name, message);  // 通过中介者发送消息
    }

    @Override
    public void receive(String message) {
        System.out.println(name + " received message: " + message);
    }
}
// 具体中介者：智能家居控制器
class SmartHomeMediator implements Mediator {
    private Map<String, Device> devices = new HashMap<String, Device>();

    public void register(String deviceName, Device device) {
        devices.put(deviceName, device);
    }

    public void relay(String sender, String message) {
        for (Map.Entry<String, Device> entry : devices.entrySet()) {
            // 发送者不需要接收自己的消息
            if (!entry.getKey().equals(sender)) {
                entry.getValue().receive(message);
            }
        }
    }
}
class Client9 {
    public static void main(String[] args) {
        // 创建中介者（智能家居控制器）
        Mediator mediator = new SmartHomeMediator();

        // 创建具体设备，并通过中介者进行注册
        Device light = new Light(mediator);
        Device tv = new TV(mediator);
        Device airConditioner = new AirConditioner(mediator);

        mediator.register("Light", light);
        mediator.register("TV", tv);
        mediator.register("AirConditioner", airConditioner);

        // 设备间通过中介者传递消息
        light.send("开灯");
        tv.send("开TV");
        airConditioner.send("开空调");
    }
}
